/*
 * Copyright Radosław Smogura, 2012. All rights reserved.
 *
 * The content of this file is confidential and it is intelectual property
 * of copyright owners.
 * 
 *
 * $URL: http://reprap-ide.googlecode.com/svn/trunk/RepRapIDE/RepRapProject/src/main/java/eu/softper/reprap/project/RepRapNewProjectPanel.java $
 * $Id: RepRapNewProjectPanel.java 3 2012-11-19 10:58:30Z mail@smogura.eu $
 * $Revision: 3 $
 */
package eu.softper.reprap.project;

import java.awt.Component;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.openide.WizardDescriptor;
import org.openide.util.HelpCtx;

/**
 *
 * @author rsmogura
 */
public class RepRapNewProjectPanel extends javax.swing.JPanel implements WizardDescriptor.Panel, WizardDescriptor.FinishablePanel {
    private WizardDescriptor wd;
    private RepRapProjectConfig config;
    
    private static final String defaultDir;
    static {
        String dir = null;
        try {
            dir = System.getProperty("user.home");
        }catch(SecurityException ignored) {
        }finally {
            defaultDir = dir;
        }
    }
    public RepRapNewProjectPanel(WizardDescriptor wd, RepRapProjectConfig config) {
        this();
        this.wd = wd;
        this.config = config;
    }
    
    
    /**
     * Creates new form RepRapNewProjectPanel
     */
    private RepRapNewProjectPanel() {
        initComponents();
        jBaseDirectory.setText(defaultDir);
        
        jBaseDirectory.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                recalculateDirs();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                recalculateDirs();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
               recalculateDirs();
            }
        });
        
        jProjectName.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                recalculateDirs();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                recalculateDirs();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
               recalculateDirs();
            }
        });
    }
    
    public String getTargetDirectory() {
        return jFinalDirectory.getText();
    }

    private void recalculateDirs() {
        String projectName = jProjectName.getText();
        if (projectName == null || projectName.trim().isEmpty()) {
            wd.setValid(false);
            jMessageLabel.setText("Specify non empty project name");
            return;
        }else {
            wd.setValid(true);
            jMessageLabel.setText(null);
            config.setName(projectName);
        }

        projectName = projectName.trim();
        projectName = projectName.replaceAll("\\s", "");
        projectName = projectName.replaceAll("\\\\", "");
        projectName = projectName.replaceAll("\\/", "");
        
        //Check base directory
        String baseDirectory = jBaseDirectory.getText();
        if (baseDirectory == null || baseDirectory.trim().isEmpty()) {
            wd.setValid(false);
            jMessageLabel.setText("Specify base project directory");
            return;
        }else {
            wd.setValid(true);
            jMessageLabel.setText(null);
        }
        
        //Check if base directory exists and it's directory        
        File baseDirF = new File(baseDirectory);
        try {
            String message = null;            
            if (!baseDirF.exists()) {
                message = "Base directory do not exists.";
            }else if (!baseDirF.isDirectory()) {
                message = "Base directory is not directory - specify directory.";
            }
            
            if (message != null) {
                wd.setValid(false);
                jMessageLabel.setText(message);
                return;
            }else {
               wd.setValid(true);
               jMessageLabel.setText(null);
            }
        }catch(Exception e) {
            throw new RuntimeException(e);
        }
                
        //Check if target directory do not exists
        File f = new File(baseDirF, projectName);
        if (f.exists()) {
            wd.setValid(false);
            jMessageLabel.setText("Terget directory already exists.");
        }else {
            wd.setValid(true);
            jMessageLabel.setText(null);
            jFinalDirectory.setText(f.getAbsolutePath());
        }
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jProjectName = new javax.swing.JTextField();
        jOpenDirectory = new javax.swing.JButton();
        jBaseDirectory = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        jFinalDirectory = new javax.swing.JTextField();
        jMessageLabel = new javax.swing.JLabel();

        jLabel1.setText(org.openide.util.NbBundle.getMessage(RepRapNewProjectPanel.class, "RepRapNewProjectPanel.jLabel1.text")); // NOI18N

        jLabel2.setText(org.openide.util.NbBundle.getMessage(RepRapNewProjectPanel.class, "RepRapNewProjectPanel.jLabel2.text")); // NOI18N

        jProjectName.setText(org.openide.util.NbBundle.getMessage(RepRapNewProjectPanel.class, "RepRapNewProjectPanel.jProjectName.text")); // NOI18N
        jProjectName.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jProjectNamePropertyChange(evt);
            }
        });

        jOpenDirectory.setText(org.openide.util.NbBundle.getMessage(RepRapNewProjectPanel.class, "RepRapNewProjectPanel.jOpenDirectory.text")); // NOI18N
        jOpenDirectory.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jOpenDirectoryActionPerformed(evt);
            }
        });

        jBaseDirectory.setText(org.openide.util.NbBundle.getMessage(RepRapNewProjectPanel.class, "RepRapNewProjectPanel.jBaseDirectory.text")); // NOI18N
        jBaseDirectory.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jBaseDirectoryPropertyChange(evt);
            }
        });

        jLabel3.setText(org.openide.util.NbBundle.getMessage(RepRapNewProjectPanel.class, "RepRapNewProjectPanel.jLabel3.text")); // NOI18N

        jFinalDirectory.setEditable(false);
        jFinalDirectory.setText(org.openide.util.NbBundle.getMessage(RepRapNewProjectPanel.class, "RepRapNewProjectPanel.jFinalDirectory.text")); // NOI18N
        jFinalDirectory.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jFinalDirectoryPropertyChange(evt);
            }
        });

        jMessageLabel.setText(org.openide.util.NbBundle.getMessage(RepRapNewProjectPanel.class, "RepRapNewProjectPanel.jMessageLabel.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jMessageLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jProjectName))
                    .addComponent(jSeparator1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBaseDirectory, javax.swing.GroupLayout.DEFAULT_SIZE, 531, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jOpenDirectory))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jFinalDirectory)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jLabel2, jLabel3});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jProjectName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jOpenDirectory)
                    .addComponent(jBaseDirectory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jFinalDirectory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 69, Short.MAX_VALUE)
                .addComponent(jMessageLabel))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jFinalDirectoryPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jFinalDirectoryPropertyChange
        if ("text".equals(evt.getPropertyName())) {
            recalculateDirs();
        }
    }//GEN-LAST:event_jFinalDirectoryPropertyChange

    private void jProjectNamePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jProjectNamePropertyChange
        if ("text".equals(evt.getPropertyName())) {
            recalculateDirs();
        }
    }//GEN-LAST:event_jProjectNamePropertyChange

    private void jBaseDirectoryPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jBaseDirectoryPropertyChange
        if ("text".equals(evt.getPropertyName())) {
            recalculateDirs();
        }
    }//GEN-LAST:event_jBaseDirectoryPropertyChange

    private void jOpenDirectoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jOpenDirectoryActionPerformed
       JFileChooser fc = new JFileChooser(defaultDir);
       fc.setDialogType(JFileChooser.OPEN_DIALOG);
       fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
       
       if (fc.showDialog(this, "Open") == JFileChooser.APPROVE_OPTION) {
           jBaseDirectory.setText(fc.getSelectedFile().getAbsolutePath());
           recalculateDirs();
       }
    }//GEN-LAST:event_jOpenDirectoryActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField jBaseDirectory;
    private javax.swing.JTextField jFinalDirectory;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jMessageLabel;
    private javax.swing.JButton jOpenDirectory;
    private javax.swing.JTextField jProjectName;
    private javax.swing.JSeparator jSeparator1;
    // End of variables declaration//GEN-END:variables

    @Override
    public Component getComponent() {
        return this;
    }

    @Override
    public HelpCtx getHelp() {
        return null;
    }

    @Override
    public void readSettings(Object settings) {
    }

    @Override
    public void storeSettings(Object settings) {
    }

    @Override
    public void addChangeListener(ChangeListener l) {
    }

    @Override
    public void removeChangeListener(ChangeListener l) {
    }

    @Override
    public boolean isFinishPanel() {
        return true;
    }
}
